<template>
  <div class="container">
    <div class="main-content">
      <!-- 左侧页面管理区域 -->
      <div class="left-side">
        <div class="page-management">
          <div class="header">
            <span class="title">页面</span>
            <el-button type="primary" @click="addNewPage">添加页面</el-button>
          </div>
          
          <div class="page-list">
            <div 
              v-for="page in pages" 
              :key="page.id"
              class="page-item"
              :class="{ 'active': activePageId === page.id }"
              @click="switchPage(page.id)"
            >
              <span class="page-name">{{ page.name }}</span>
              <el-button
                v-if="page.id !== 'index1'"
                class="delete-btn"
                type="danger"
                link
                @click.stop="confirmDelete(page.id)"
              >
                ×
              </el-button>
            </div>
          </div>
        </div>

        <!-- 底部常驻区域移动到左侧 -->
        <div class="footer">
          <span class="version">LUHUO v1.1.0</span>
          <el-button type="primary" @click="exportAllPages">导出</el-button>
        </div>
      </div>

      <!-- 右侧页面编辑区域 -->
      <div class="right-side">
        <div 
          v-for="page in pages" 
          :key="page.id"
          class="page-editor"
          v-show="activePageId === page.id"
        >
          <CodeGenerator 
            :ref="(el: any) => setEditorRef(page.id, el)"
            :page-id="page.id"
            :active="activePageId === page.id"
            @updateCode="(code) => updatePageCode(page.id, code)"
          />
        </div>
      </div>
    </div>
  </div>

  <!-- 页面选择对话框 -->
  <el-dialog v-model="showPageDialog" title="选择跳转页面" width="400px">
    <el-select v-model="selectedPage" placeholder="请选择页面" style="width: 100%;">
      <el-option 
        v-for="page in availablePages" 
        :key="page.id" 
        :label="page.name" 
        :value="page.name"
      />
    </el-select>
    <template #footer>
      <el-button @click="showPageDialog = false">取消</el-button>
      <el-button type="primary" @click="confirmPageSelection">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onBeforeUnmount, onMounted, onUnmounted, toRaw } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import CodeGenerator from '@/components/CodeGenerator.vue'
import { vscode } from '@/utils/vscode'
import { convertToBlueOSCodeFromHtml } from '@/utils/codeConverter';
import { convertCodeToMarkdown } from '@/utils/markdown-helper';

// 新增状态管理
const showPageDialog = ref(false);
const selectedPage = ref('');
const selectedElementId = ref<string | null>(null);
const codeGeneratorRefs = ref<Record<string, any>>({})
const currentPageId = ref<string>('')

// 使用函数式 ref 获取组件实例
const setEditorRef = (pageId: string, el: InstanceType<typeof CodeGenerator>) => {
  try {
    if (el) {
      codeGeneratorRefs.value[pageId] = el
    }
  } catch (error) {
    console.error('设置 CodeGenerator 引用失败:', error)
  }
}

// 计算可用的页面列表
const availablePages = computed(() => {
  return pages.value.filter(page => page.id !== activePageId.value);
});

// 处理iframe消息时增加页面ID验证
const handleIframeMessage = (event: MessageEvent) => {
  if (event.data.action === 'showPageSelector' && event.data.pageId === activePageId.value) {
    selectedElementId.value = event.data.elementId
    currentPageId.value = event.data.pageId
    showPageDialog.value = true
  }
}

// 生命周期钩子
onMounted(() => {
  window.addEventListener('message', handleIframeMessage);
});

onUnmounted(() => {
  window.removeEventListener('message', handleIframeMessage);
});

onBeforeUnmount(() => {
  // 清理所有 iframe 引用
  Object.keys(codeGeneratorRefs.value).forEach(pageId => {
    delete codeGeneratorRefs.value[pageId]
  })
})

// 确认选择时指定目标iframe
const confirmPageSelection = () => {
  if (selectedPage.value && currentPageId.value) {
    const currentCodeGenerator = codeGeneratorRefs.value[currentPageId.value]
    if (currentCodeGenerator) {
      const previewIframe = toRaw(currentCodeGenerator).getIframe()
      if (previewIframe) {
        previewIframe.contentWindow?.postMessage({
          action: 'updateOnclick',
          elementId: selectedElementId.value,
          pageName: selectedPage.value
        }, '*')

        const iframeDoc = previewIframe.contentDocument
        const element = iframeDoc.getElementById(selectedElementId.value ? selectedElementId.value : '')
        if (element) {
          // 更新元素属性
          element.setAttribute('onclick', `jumpTo('/pages/${selectedPage.value}')`)
          const selector = `style[nonce="2lMU328qsiz5m7PJbUcbO7Flx4ZFVQqQ"], script[nonce="2lMU328qsiz5m7PJbUcbO7Flx4ZFVQqQ"]`;
          iframeDoc.querySelectorAll(selector).forEach((tag: any) => tag.remove());

          // 获取更新后的完整HTML
          const updatedHtml = iframeDoc.documentElement.outerHTML
          toRaw(currentCodeGenerator).markdownContent = convertCodeToMarkdown(updatedHtml, 'html')
        }
      }
    }

    // 重置状态
    showPageDialog.value = false
    selectedPage.value = ''
    currentPageId.value = ''
  }
}

interface Page {
  id: string
  name: string
  code: string
}

const pages = ref<Page[]>([
  { id: 'index1', name: 'index1', code: '' }
])

const activePageId = ref<string>('index1')

let pageCounter = 1

const addNewPage = () => {
  pageCounter++
  const newPage = {
    id: `index${pageCounter}`,
    name: `index${pageCounter}`,
    code: ''
  }
  pages.value.push(newPage)
  switchPage(newPage.id)
}

const switchPage = (id: string) => {
  activePageId.value = id
}

const confirmDelete = (id: string) => {
  ElMessageBox.confirm('确定要删除这个页面吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deletePage(id)
  })
}

const deletePage = (id: string) => {
  if (id === 'index1') return
  
  const index = pages.value.findIndex(p => p.id === id)
  if (index > -1) {
    pages.value.splice(index, 1)
    
    if (activePageId.value === id) {
      activePageId.value = 'index1'
    }

    delete codeGeneratorRefs.value[id]
  }
}

const updatePageCode = (id: string, code: string) => {
  const page = pages.value.find(p => p.id === id)
  if (page) {
    console.log(id + '更新代码')
    page.code = code
  }
}

const exportAllPages = () => {
  const pagesToExport = pages.value.filter(p => p.code)
  if (!pagesToExport.length) {
    ElMessage.warning('没有可导出的页面内容')
    return
  }

  vscode.postMessage({
    command: 'exportPages',
    pages: pagesToExport.map(p => ({
      name: `${p.name}`,
      content: convertToBlueOSCodeFromHtml(p.code)
    }))
  })
}

</script>


<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.left-side {
  min-width: 200px;
  border-right: 1px solid var(--vscode-panel-border);
  display: flex;
  flex-direction: column;
  height: 100%;
}

.right-side {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.page-management {
  display: flex;
  flex-direction: column;
  flex: 1;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

.page-list {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  overflow-y: auto;
  flex: 1;
}

.page-item {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  border: 1px solid var(--vscode-panel-border);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  background-color: var(--vscode-sideBar-background);
}

.page-item:hover {
  background-color: var(--vscode-list-hoverBackground);
}

.page-item.active {
  color: var(--vscode-button-foreground);
  border-color: var(--vscode-button-background);
  background-color: var(--vscode-list-activeSelectionBackground);
}

.delete-btn {
  margin-left: 8px;
  padding: 0;
  width: 20px;
  height: 20px;
  flex-shrink: 0;
}

.page-name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.footer {
  border-top: 1px solid var(--vscode-panel-border);
  padding: 12px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.version {
  color: var(--vscode-descriptionForeground);
  font-size: 12px;
}

.page-editor {
  flex: 1;
}
</style>
